﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using BEGDC.PreContract.BLL;

namespace PreContractWeb.Administration
{
    public partial class EditCAT : System.Web.UI.Page
    {
        private BEGDC.PreContract.BLL.Authentication.PCIdentity user;

        protected void Page_Load(object sender, EventArgs e)
        {

            Page.Header.Controls.Add(new LiteralControl(@"<base target=""_self"" />"));
            user = new BEGDC.PreContract.BLL.Authentication.PCIdentity(HttpContext.Current.User.Identity);
            
            if (!ReportHelper.IsAdmin(user.EmployeeId))
            {
                this.divError.InnerHtml = AlertMessage.NoAdminPermission;
                this.divConnect.Visible = false;
                this.divError.Visible = true;
            } 

            else if (!IsPostBack)
            {
                if (Request["id"] != null)
                    if (Request["id"] == "-1")
                    {
                        this.SaveButton.Text = "添加(Add)";
                        this.CNTitleLabel.Text = "添加大客户";
                        this.ENTitleLabel.Text = "Add A CAT";
                    }
                    else
                    {
                        this.SaveButton.Text = "保存(Save)";
                        this.CNTitleLabel.Text = "编辑大客户信息";
                        this.ENTitleLabel.Text = "Edit CAT Information";
                        this.LoadData();
                    }

                Response.Cache.SetCacheability(HttpCacheability.NoCache);
            }
        }

        protected void LoadData()
        {
            try
            {
                int catID = int.Parse(Request["id"].ToString());

                BEGDC.PreContract.BLL.ICAT iCAT = (BEGDC.PreContract.BLL.ICAT)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_CAT_Service];
                BEGDC.PreContract.DAL.CAT cat = iCAT.GetCAT(catID);

                this.CATNameTextBox.Text = cat.CATName;
                this.CodeTextBox.Text = cat.CATCode;
                this.ShortCodeTextBox.Text = cat.CATCode_Shortening;
                this.SortNumberTextBox.Text = cat.SortNumber.ToString();
                this.ActiveCheckBox.Checked = cat.Active;

                //Joan 2008-10-20 date label format
                DateTime date;
                if (cat.CreateDate != Nullables.NullableDateTime.Default)
                {
                    date = System.Convert.ToDateTime(cat.CreateDate.Value);
                    this.CreateDateLabel.Text = date.ToString("yyyy-MM-dd") + " " + date.ToShortTimeString();
                }

                if (cat.UpdateDate != Nullables.NullableDateTime.Default)
                {
                    date = System.Convert.ToDateTime(cat.UpdateDate.Value);
                    this.UpdateDateLabel.Text = date.ToString("yyyy-MM-dd") + " " + date.ToShortTimeString();
                }
                //this.CreateDateLabel.Text = cat.CreateDate.ToString();
                //this.UpdateDateLabel.Text = cat.UpdateDate.ToString();

                //end
            }

            catch (Exception ex)
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + ex.Message.Replace("'", "\\'") + "')</script>");
            }

        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {
            try
            {
                int catID = int.Parse(Request["id"].ToString());
                bool flag = true;
                BEGDC.PreContract.BLL.ICAT iCAT = (BEGDC.PreContract.BLL.ICAT)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_CAT_Service];

                if (this.IsCATCodeExist(this.CodeTextBox.Text.Trim(),this.ShortCodeTextBox.Text.Trim(),catID))
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + BaseFunction.ChangeAlertMessage(AlertMessage.ExistedRecord) + "')</script>");
                    return;
                }

                if (this.IsSortNumberExist(this.SortNumberTextBox.Text.Trim(),catID))
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + BaseFunction.ChangeAlertMessage(AlertMessage.HasSortNumber) + "')</script>");
                    return;
                }

                if (catID == -1)
                {
                    int numflag = iCAT.AddCAT(this.CodeTextBox.Text.Trim(), this.ShortCodeTextBox.Text.Trim(), this.CATNameTextBox.Text.Trim(),
                        Convert.ToInt32(this.SortNumberTextBox.Text.Trim()), this.ActiveCheckBox.Checked, System.DateTime.Now,System.DateTime.Now);
                    if (numflag == 0)
                        flag = false;
                }
                else
                {
                    BEGDC.PreContract.DAL.CAT cat = iCAT.GetCAT(catID);

                    flag = iCAT.UpdateCAT(catID,this.CodeTextBox.Text.Trim(),this.ShortCodeTextBox.Text.Trim(),this.CATNameTextBox.Text.Trim(),
                        Convert.ToInt32(this.SortNumberTextBox.Text.Trim()),this.ActiveCheckBox.Checked,cat.CreateDate,System.DateTime.Now);
                }

                if (!flag)
                {
                    this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + AlertMessage.ExistedRecord + "')</script>");
                    return;
                }
                this.Response.Write("<script language='javascript'>alert('" + BaseFunction.ChangeAlertMessage(AlertMessage.OperationSuccess) + "');var arr=new Array(); arr[0]=0; window.returnValue=arr;window.close();</script>");

            }
            catch (Exception ex)
            {
                this.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + ex.Message.Replace("'", "\\'") + "')</script>");
            }
        }

        protected bool IsCATCodeExist(string catCode,string shortCode, int catID)
        {
            string condtion = String.Format("(CATCode = '{0}' OR CATCode_Shortening = '{1}')", catCode,shortCode);

            if (!catID.Equals(String.Empty))
                condtion += String.Format("AND CATID <> {0}", catID);

            BEGDC.PreContract.BLL.ICAT iCat = (BEGDC.PreContract.BLL.ICAT)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_CAT_Service];
            DataTable dt = iCat.GetCAT_DataTable(condtion);

            if (dt.Rows.Count == 0)
                return false;
            else
                return true;

        }

        protected bool IsSortNumberExist(string sortNumber, int catID)
        {
            string condition = String.Format("SortNumber = '{0}'", sortNumber);

            if (catID != -1)
                condition += String.Format(" AND CATID <> {0}", catID);

            BEGDC.PreContract.BLL.ICAT iCat = (BEGDC.PreContract.BLL.ICAT)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_CAT_Service];
            DataTable dt = iCat.GetCAT_DataTable(condition);

            if (dt.Rows.Count == 0)
                return false;
            else
                return true;
        }
    }
}
